<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/27
 * Time: 19:14
 */

namespace app\sun\controller;


use app\common\controller\SunBaseController;
use app\common\helper\StringHelper;
use app\sun\model\Admin;
use app\sun\service\AdminService;


class AdminController extends SunBaseController
{
    /**
     * 管理员列表
     * @return \think\Response
     */
    public function adminList()
    {
        $list = Admin::paginate();

        $this->assign('list', $list);

        return $this->returnHtml();
    }

    /**
     * 编辑管理员
     * @return \think\Response
     */
    public function adminEdit()
    {
        if($this->request->isPost()){

            $postData = $this->request->post();

            if(empty($postData['password'])){
                unset($postData['password']);
            }else{
                $admin = Admin::get($postData['id']);

                $postData['password'] = md5(md5($postData['password']) . $admin['salt']);
            }

            $id = AdminService::save($postData);

            if($id){
                return $this->returnJson(1, '添加成功');
            }else{
                return $this->returnJson(0, '添加失败');
            }
        }

        $id = input('id');

        $admin = Admin::get($id);


        $this->assign('admin', $admin);

        return $this->returnHtml();
    }

    /**
     * 新增管理员
     * @return \think\Response
     */
    public function adminAdd()
    {

        if($this->request->isPost()){

            $postData = $this->request->post();

            if(empty($postData['password'])){
                return $this->returnJson(0, '密码必填！');
            }

            $postData['salt'] = StringHelper::strRand(4);

            $postData['password'] = md5(md5($postData['password']) . $postData['salt']);


            $id = AdminService::save($postData);

            if($id){
                return $this->returnJson(1, '添加成功');
            }else{
                return $this->returnJson(0, '添加失败');
            }
        }

        return $this->returnHtml();
    }

    /**
     * 删除管理员
     * @return \think\Response
     */
    public function adminDel()
    {
        if($this->request->isPost()){

            $id = input('id');

            $id = max(0, intval($id));

            if(empty($id)){
                return $this->returnJson(0, '缺少参数！');
            }

            $result = AdminService::del($id);

            if($result){
                return $this->returnJson(1, '删除成功！');
            }else{
                return $this->returnJson(0, '删除失败！');
            }
        }

        return $this->returnJson(0, '请使用POST提交！');
    }

}